package com.mayuanfei.springboot15.controller;

import cn.hutool.core.bean.BeanUtil;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import com.mayuanfei.springboot15.common.Constants;
import com.mayuanfei.springboot15.pojo.UserInfo1;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * Hazelcast的全局序列化器
 *
 * @author 老马
 * @date 2023-07-24 17:04
 */
@RestController
public class GlobalController {

    @Resource
    private HazelcastInstance hazelcastInstance;

    @PostMapping(value = "/writeGlobal")
    public UserInfo1 writeDataToHazelcast(String userId, String userName, Integer age) {
        UserInfo1 userInfo = new UserInfo1();
        userInfo.setUserId(userId);
        userInfo.setUserName(userName);
        userInfo.setAge(age);
        IMap<String, UserInfo1> map = hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
        map.put(userId, userInfo);
        return userInfo;
    }

    @GetMapping(value = "/readOneGlobal")
    public UserInfo1 readDataFromHazelcast(String userId) {
        IMap<String, UserInfo1> map = hazelcastInstance.getMap(Constants.CACHE_NAME_SESSION_USERS);
        Object userInfo1 = map.get(userId);
        return BeanUtil.toBean(userInfo1, UserInfo1.class);
    }
}